﻿///<reference path="/scripts/Awesome.js" />
///<reference path="/scripts/AwesomeQuery.js" />

Table.Extensions.Add(new Extension("sortable", SortableTable));
function SortableTable(e) {
    if (this.DOM === undefined) {
        return SortableTable.Inherit(SortableTable.Extend(new Table(e).ClassName("sortable")));
    }

    var $ = this;
    e = $.DOM;
    var c;
    if (this.Head == null) {
        this.SetHead(new TableHead());
        this.Head.Rows.Add(new Row());
        c = this.Rows[0].Cells.Copy();
        this.Rows[0].Cells.Clear();
        this.Head.Rows[0].Cells.AddRange(c);
    }

    this.Items = this.Index();

    var h = this.Head.Rows[0].Cells, l = h.length, i;
    for (i = 0; i < h; i++) {
        h[i].OnClick.Add(new Delegate(this.Sort, this, h[i]));
    }
}

SortableTable.prototype.Index = function () {
    var a = this.Rows, b = [], c, k, j, l = a.length, i, o, v, h = this.Head.Rows[0].Cells, t, x;
    for (i = 0; i < l; i++) {
        o = {};
        c = a[i].Cells, k = c.length;
        for (j = 0; j < k; j++) {
            v = c[j];
            t = h[j].Text().Trim();
            x = v.Text();
            if (x.IsFloat()) {
                x = x.ToFloat();
            }
            else if (x.IsDateTime()) {
                x = x.ToDateTime();
            }

            o[t] = x;
        }
        o.__Row = a[i];
        b.Add(o);
    }

    return b;
};

SortableTable.prototype.Sort = function (h) {
    var t = h.Text().Trim(), r = this.Rows, l = r.length, i;
    a.Sort(t);
    this.Rows.BeginUpdate();
    this.Rows.Clear();
    for (i = 0; i < l; i++) {
        this.Add(a[i].__Row);
    }

    this.Rows.EndUpdate();
};